'''
log.py
Nicholas Swartzendruber

The log class is used to write logs to files,
and keep single variable data in files.

For example, time of the last tweet needs to be saved,
it can be done with using log.put(key, value), and retrieved
with log.get(key, value).
'''
from time import strftime
import os

data_dir = 'data/'

class Log:
  
  @staticmethod
  def println(text, file = None):
    '''
    The print method is used to append to the end
    of a log file. Uses:
    1) By leaving the optional file parameter blank,
    a default log file will be written to. This log
    file can be found in "<current-dir>/log/<date>.txt".
    A time stamp will be produced on each println. 
    
    2)By passing a file or directory path (that ends
    in .txt), the text will be appended to the end of
    that file. A time stamp will not be produced 
    automatically.
    '''
    timestamp = ''
    if file == None:
      file = 'logs/' + strftime("%Y_%m_%d") + '.txt'
      timestamp = strftime("%H:%M:%S") + " >> "
    
    last_index = len(file) - 1 - file[::-1].find('/')
    path = file[:last_index]
    if '/' in file and not os.path.exists(path):
      os.mkdir(path)
    with open(file, 'a+') as f:
          f.write(str(timestamp + text + '\n'))
          print str(timestamp + text)
          
  @staticmethod        
  def put(key, value):
    '''
    Used to store persistent data. Loads the
    value into a key, and stores it for later use.
    '''
    
    #First, make a directory.
    if not os.path.exists(data_dir):
      os.mkdir(data_dir)
      
    with open(data_dir + key + '.txt', 'w+') as f:
      f.write(str(value))
  
  @staticmethod
  def get(key):
    '''
    Used to get the value at the specific key. 
    Returns the value if found, or False if not.
    '''
    try:
      with open(data_dir + key + '.txt', 'r') as f:
        return f.readline()
    except IOError:
      return False
    
  
          
'''
Test the log class
'''
if __name__ == '__main__': 
  print Log.get('Hi')
  Log.put("Hi", 5)
  print Log.get('Hi')
  print 'finished'